<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基础镜像管理" name="base">
          <el-button type="primary" class="mb-4" @click="handleAdd">上传镜像</el-button>
          <el-table :data="baseImages.slice((basePage.currentPage - 1) * basePage.pageSize, basePage.currentPage * basePage.pageSize)" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="60" />
            <el-table-column prop="name" label="镜像名称" />
            <el-table-column prop="artifact_count" label="制品数量" width="100" />
            <el-table-column prop="project_id" label="项目ID" width="100" />
            <el-table-column prop="pull_count" label="拉取次数" width="100" />
            <el-table-column label="创建时间" width="120">
              <template slot-scope="scope">
                <span>{{ formatTime(scope.row.creation_time) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" width="120">
              <template slot-scope="scope">
                <span>{{ formatTime(scope.row.update_time) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="标签" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.tags ? scope.row.tags.join(', ') : '无' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button size="small" type="primary" @click="handleUpdateBase(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteBase(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleBaseSizeChange"
            @current-change="handleBaseCurrentChange"
            :current-page="basePage.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="basePage.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="baseImages.length"
            class="pagination-container"
          />
        </el-tab-pane>

        <el-tab-pane label="服务镜像管理" name="service">
          <el-button type="primary" class="mb-4" @click="handleAdd">上传服务镜像</el-button>
          <el-table :data="serviceImages.slice((servicePage.currentPage - 1) * servicePage.pageSize, servicePage.currentPage * servicePage.pageSize)" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="60" />
            <el-table-column prop="name" label="镜像名称" />
            <el-table-column prop="project_name" label="项目名称" width="120" />
            <el-table-column prop="artifact_count" label="制品数量" width="100" />
            <el-table-column prop="project_id" label="项目ID" width="100" />
            <el-table-column prop="pull_count" label="拉取次数" width="100" />
            <el-table-column label="创建时间" width="120">
              <template slot-scope="scope">
                <span>{{ formatTime(scope.row.creation_time) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" width="120">
              <template slot-scope="scope">
                <span>{{ formatTime(scope.row.update_time) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="标签" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.tags ? scope.row.tags.join(', ') : '无' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button size="small" @click="handleVersion(scope.row)">版本</el-button>
                  <el-button size="small" type="primary" @click="handleUpdateService(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDeleteService(scope.row)">删除</el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleServiceSizeChange"
            @current-change="handleServiceCurrentChange"
            :current-page="servicePage.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="servicePage.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="serviceImages.length"
            class="pagination-container"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 上传/编辑镜像 Dialog -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="500px">
      <el-form label-width="100px" ref="formRef" :model="form" :rules="rules">
        <el-form-item label="镜像名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item v-if="activeTab==='service'" label="项目名称" prop="project_name">
          <el-input v-model="form.project_name" />
        </el-form-item>
        <el-form-item v-if="activeTab==='base'" label="框架" prop="framework">
          <el-select v-model="form.framework">
            <el-option label="TensorFlow" value="TensorFlow" />
            <el-option label="PyTorch" value="PyTorch" />
            <el-option label="PaddlePaddle" value="PaddlePaddle" />
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveImage">保存</el-button>
      </template>
    </el-dialog>

    <!-- 上传镜像文件 Dialog -->
    <el-dialog :visible.sync="uploadDialogVisible" title="上传服务镜像文件" width="500px">
      <el-form label-width="100px">
        <el-form-item label="镜像文件">
          <el-upload
            ref="upload"
            action=""
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :file-list="selectedFile ? [selectedFile] : []"
            accept=".tar">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传.tar格式的镜像文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="uploadDialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="uploadLoading" @click="uploadFile">上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listBaseImages, listServiceImages, addBaseImage, addServiceImage, updateBaseImage, updateServiceImage, delBaseImage, delServiceImage, uploadServiceImageFile } from "@/api/package/image";

export default {
  name: 'ImageManagement',
  data() {
    return {
      activeTab: "base",
      baseImages: [],
      serviceImages: [],
      basePage: {
        currentPage: 1,
        pageSize: 10
      },
      servicePage: {
        currentPage: 1,
        pageSize: 10
      },
      dialogVisible: false,
      dialogTitle: "",
      uploadDialogVisible: false,
      uploadLoading: false,
      selectedFile: null,
      form: { id: undefined, name: "", version: "", framework: "", tenant: "" },
      rules: {
        name: [{ required: true, message: "镜像名称不能为空", trigger: "blur" }],
        framework: [{ required: true, message: "框架不能为空", trigger: "blur" }],
        project_name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 获取基础镜像列表
    async getBaseImageList() {
      try {
        const response = await listBaseImages();
        this.baseImages = response.images;
      } catch (error) {
        console.error('获取基础镜像列表失败:', error);
        this.$message.error('获取基础镜像列表失败，请稍后重试');
      }
    },

    // 获取服务镜像列表
    async getServiceImageList() {
      try {
        const response = await listServiceImages();
        // 将按项目分组的镜像数据展平
        this.serviceImages = response.images ? response.images.flatMap(project => 
          project.images.map(image => ({
            ...image,
            project_name: project.project_name
          }))
        ) : [];
      } catch (error) {
        console.error('获取服务镜像列表失败:', error);
        this.$message.error('获取服务镜像列表失败，请稍后重试');
      }
    },

    // 获取所有数据
    getList() {
      this.getBaseImageList();
      this.getServiceImageList();
    },

    // 新增按钮操作
    handleAdd() {
      if (this.activeTab === "service") {
        // 服务镜像管理 - 显示文件上传对话框
        this.uploadDialogVisible = true;
        this.selectedFile = null;
      } else {
        // 基础镜像管理 - 显示表单对话框
        this.form = { id: undefined, name: "", version: "", framework: "", tenant: "" };
        this.dialogTitle = "添加基础镜像";
        this.dialogVisible = true;
      }
    },

    // 修改基础镜像按钮操作
    handleUpdateBase(row) {
      this.form = { ...row };
      this.dialogTitle = "修改基础镜像";
      this.dialogVisible = true;
    },

    // 修改服务镜像按钮操作
    handleUpdateService(row) {
      this.form = { ...row };
      this.dialogTitle = "修改服务镜像";
      this.dialogVisible = true;
    },

    // 删除基础镜像按钮操作
    async handleDeleteBase(row) {
      try {
        await this.$confirm('确定要删除该基础镜像吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const imageId = row.id;
        await delBaseImage(imageId);
        this.$message.success('删除成功');
        this.getBaseImageList();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除基础镜像失败:', error);
          this.$message.error('删除基础镜像失败，请稍后重试');
        }
      }
    },

    // 删除服务镜像按钮操作
    async handleDeleteService(row) {
      try {
        await this.$confirm('确定要删除该服务镜像吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const imageId = row.id;
        await delServiceImage(imageId);
        this.$message.success('删除成功');
        this.getServiceImageList();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除服务镜像失败:', error);
          this.$message.error('删除服务镜像失败，请稍后重试');
        }
      }
    },

    async saveImage() {
      try {
        const valid = await this.$refs.formRef.validate();
        if (!valid) return;

        if (this.form.id !== undefined) {
          // 修改
          if (this.activeTab === "base") {
            await updateBaseImage(this.form);
            this.$message.success('修改基础镜像成功');
            this.getBaseImageList();
          } else {
            await updateServiceImage(this.form);
            this.$message.success('修改服务镜像成功');
            this.getServiceImageList();
          }
        } else {
          // 新增
          if (this.activeTab === "base") {
            await addBaseImage(this.form);
            this.$message.success('添加基础镜像成功');
            this.getBaseImageList();
          } else {
            await addServiceImage(this.form);
            this.$message.success('添加服务镜像成功');
            this.getServiceImageList();
          }
        }
        this.dialogVisible = false;
      } catch (error) {
        console.error('保存镜像失败:', error);
        this.$message.error('保存镜像失败，请稍后重试');
      }
    },

    // 基础镜像分页大小改变
    handleBaseSizeChange(val) {
      this.basePage.pageSize = val;
      this.basePage.currentPage = 1;
    },

    // 基础镜像当前页改变
    handleBaseCurrentChange(val) {
      this.basePage.currentPage = val;
    },

    // 服务镜像分页大小改变
    handleServiceSizeChange(val) {
      this.servicePage.pageSize = val;
      this.servicePage.currentPage = 1;
    },

    // 服务镜像当前页改变
    handleServiceCurrentChange(val) {
      this.servicePage.currentPage = val;
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },

    // 版本按钮操作
    handleVersion(row) {
      this.$message.info(`查看镜像 ${row.name} 的版本信息`);
      // 这里可以添加跳转到版本管理页面的逻辑
    },

    // 文件选择变化
    handleFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.selectedFile = file.raw;
      } else {
        this.selectedFile = null;
      }
    },

    // 上传文件
    async uploadFile() {
      try {
        if (!this.selectedFile) {
          this.$message.warning('请选择要上传的文件');
          return;
        }

        // 检查文件格式
        if (!this.selectedFile.name.endsWith('.tar')) {
          this.$message.warning('只能上传.tar格式的文件');
          return;
        }

        this.uploadLoading = true;
        
        // 创建FormData并添加文件
        const formData = new FormData();
        formData.append('image', this.selectedFile);

        try {
          const response = await uploadServiceImageFile(formData);
          // 现在使用独立的axios实例，response是完整的响应对象，数据在response.data中
          if (response.data && response.data.code === 200) {
            this.$message.success('上传成功，任务已创建');
            this.uploadDialogVisible = false;
            this.selectedFile = null;
            // 刷新服务镜像列表
            this.getServiceImageList();
          } else {
            this.$message.error(response.data?.msg || '上传失败');
          }
        } catch (error) {
          console.error('上传文件失败:', error);
          // 处理错误响应，可能包含错误信息
          if (error.response && error.response.data) {
            this.$message.error(error.response.data.msg || '上传失败，请稍后重试');
          } else {
            this.$message.error('上传失败，请稍后重试');
          }
        } finally {
          this.uploadLoading = false;
        }
      } catch (error) {
        console.error('上传文件失败:', error);
      }
    }
  }
};
</script>
